package Projekt;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;

import Tydzien10.OrganizerEvent;

public class OrganizerEventXML {
	
	public static void exportToXML(File file, ArrayList<OrganizerEvent> events) throws JAXBException, IOException
	{
		OrganizerEvents toSerialize = new OrganizerEvents(events);
		JAXBContext context = JAXBContext.newInstance(OrganizerEvents.class);
		Marshaller mar = context.createMarshaller();
		try(FileWriter writer = new FileWriter(file))
		{
			mar.marshal(toSerialize, writer);
		}
	}
	
	public static ArrayList<OrganizerEvent> importFromXML(File file) throws JAXBException, FileNotFoundException, IOException
	{
		ArrayList<OrganizerEvent> events = new ArrayList<OrganizerEvent>();
		JAXBContext context = JAXBContext.newInstance(OrganizerEvents.class);
		Unmarshaller unmar = context.createUnmarshaller();
		try(FileReader reader = new FileReader(file))
		{
			OrganizerEvents deserialized = (OrganizerEvents) unmar.unmarshal(reader);
			events = deserialized.unwrap();
		}
		return events;
	}
}

@XmlRootElement(name="Events")
@XmlSeeAlso(OrganizerEvent.class)
class OrganizerEvents
{
	@XmlElementWrapper(name="List")
	public ArrayList<OrganizerEvent> events;
	
	public OrganizerEvents(ArrayList<OrganizerEvent> events)
	{
		this.events = events;
	}

	@SuppressWarnings("unchecked")
	public ArrayList<OrganizerEvent> unwrap() {
		return (ArrayList<OrganizerEvent>) events.clone();
	}

	public OrganizerEvents()
	{
		this.events = null;
	}
}
